package com.jsoft.jsofted.sys.service.impl;

import com.jsoft.jsofted.sys.entity.OrgEntity;
import com.jsoft.jsofted.sys.mapper.OrgMapper;
import com.jsoft.jsofted.framework.mybatis.CocQueryWrapper;
import com.jsoft.jsofted.framework.service.impl.CocServiceImpl;
import com.jsoft.jsofted.sys.service.OrgService;
import com.jsoft.jsofted.sys.vo.OrgBean;
import com.jsoft.jsofted.sys.vo.OrgTreeMaker;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;

@Service
public class OrgServiceImpl extends CocServiceImpl<OrgMapper, OrgEntity> implements OrgService {


    public List<OrgBean> queryTree(Map queryParams) {
        List<OrgEntity> list = this.list(parseQueryWrapper(queryParams));
        return OrgTreeMaker.make(list);
    }

    @Override
    public List<OrgEntity> querylist(Map queryParams) {
        return list(this.parseQueryWrapper(queryParams));
    }


    protected CocQueryWrapper parseQueryWrapper(Map queryParams) {
        if (queryParams == null) {
            queryParams = new LinkedHashMap();
        }

        CocQueryWrapper queryWrapper = new CocQueryWrapper();
        this._parseSortParams(queryWrapper, queryParams);
        this._parseKeywordsParams(queryWrapper, queryParams);
        this._parsePostParams(queryWrapper, queryParams);

        return queryWrapper;
    }

    /**
     * 解析【条件参数】中的【职位（岗位）参数】
     * 即查询哪些单位设置了指定的职位（岗位）。
     */
    private void _parsePostParams(CocQueryWrapper queryWrapper, Map queryParams) {
        String postId = (String) queryParams.get("postId");
        if (StringUtils.hasText(postId)) {
            queryWrapper.subSelect("id", "in",
                    "(select org_id from sys_post_org where post_id = {0})", postId);
        }
    }

    /**
     * 解析【条件参数】中的【排序参数】
     */
    private void _parseSortParams(CocQueryWrapper queryWrapper, Map queryParams) {
        queryWrapper.orderByDesc("sort_value", "create_time");
    }

    /**
     * 解析【条件参数】中的【关键字参数】
     */
    private void _parseKeywordsParams(CocQueryWrapper queryWrapper, Map queryParams) {
        String keywords = (String) queryParams.get("keywords");
        if (StringUtils.hasText(keywords)) {
            Consumer<CocQueryWrapper> consumer = qw -> {
                qw.like("name", keywords);
                qw.or();
                qw.like("fullName", keywords);
            };
            queryWrapper.and(consumer);
        }
    }

}
